package cn.itcast.service.impl;

import cn.itcast.dao.TownDao;
import cn.itcast.domain.Town;
import cn.itcast.service.TownService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.util.List;

public class TownServiceImpl implements TownService {
    @Override
    public List<Town> findByName(String name) throws Exception{
        SqlSession sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")).openSession();

        TownDao townDao = sqlSession.getMapper(TownDao.class);

        List<Town> towns = townDao.findByName("%" + name + "%");

        sqlSession.close();
        return  towns;

    }

    @Override
    public PageInfo pageQuery(Integer pageNum, Integer pageSize) throws Exception {
        SqlSession sqlSession = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml")).openSession();

        TownDao townDao = sqlSession.getMapper(TownDao.class);

        PageHelper.startPage(pageNum,pageSize);

        List<Town> towns = townDao.findAll();
        PageInfo<Town> pageInfo = new PageInfo<>(towns);
        sqlSession.close();

        return pageInfo;
    }

}
